const { StatusBar, AsyncStorage } = require('react-native');
const moment = require('moment');
const { Toast } = require('antd-mobile');
import constant from "./constant";
import Validator from "./Validator";
import RouterServer from "./RouterServer";
let instance = null;
class Request {
    static getApi() {
        return Request.getInstance().Api;
    }
    ;
    static init(api, debug = true, timeout = 5000) {
        Request.getInstance().Api = api;
        Request.getInstance().debug = debug;
        Request.getInstance().timeout = timeout;
    }
    static getInstance() {
        if (!instance) {
            instance = new Request();
        }
        return instance;
    }
    static checkResponse(response, apiUrl) {
        StatusBar.setNetworkActivityIndicatorVisible(false);
        if (response.code === 200) {
            return true;
        }
        else {
            if (Request.getInstance().debug) {
                console.log('error in ', apiUrl, response);
            }
            throw new Error(Request.getErrorMessage(response));
        }
    }
    ;
    static LogError(e, from = null) {
        if (Request.getInstance().debug) {
            if (from) {
                console.log('the error from:', from);
            }
            console.log(e);
        }
        if (e.message === 'Network request failed') {
            Toast.fail('网络请求失败', constant.ToastDuration);
        }
        else if (e.message === '请登录') {
            RouterServer.replace('auth');
        }
        else {
            Toast.fail(e.message, constant.ToastDuration);
        }
    }
    static post(url, params) {
        StatusBar.setNetworkActivityIndicatorVisible(true);
        const apiUrl = Request.getInstance().Api.HOST + url;
        const timestamp = moment().format('X');
        return Request.timeout(Request.getInstance().timeout, fetch(apiUrl, {
            method: 'POST',
            headers: Request.makeHeaders(params, timestamp),
            body: Request.makeFormData(params)
        })).then((response) => {
            StatusBar.setNetworkActivityIndicatorVisible(false);
            if (response.ok === true) {
                return response.json();
            }
            else {
                const e = new Error();
                e.message = '网络错误';
                throw e;
            }
        }).then((responseData) => {
            const checked = Request.checkResponse(responseData, apiUrl);
            if (checked) {
                Request.LogSuccess(responseData, apiUrl);
                return responseData;
            }
            else {
                return null;
            }
        }).catch((e) => {
            StatusBar.setNetworkActivityIndicatorVisible(false);
            Request.LogError(e, apiUrl);
        });
    }
    static get(url, params) {
        StatusBar.setNetworkActivityIndicatorVisible(true);
        const apiUrl = Request.getInstance().Api.HOST + url + Request.makeQueryString(params);
        return Request.timeout(Request.getInstance().timeout, fetch(apiUrl, {
            method: 'GET',
        })).then((response) => {
            StatusBar.setNetworkActivityIndicatorVisible(false);
            if (response.ok === true) {
                return response.json();
            }
            else {
                const e = new Error();
                e.message = '网络错误';
                throw e;
            }
        }).then((responseData) => {
            const checked = Request.checkResponse(responseData, apiUrl);
            if (checked) {
                Request.LogSuccess(responseData, apiUrl);
                return responseData;
            }
            else {
                return false;
            }
        }).catch((e) => {
            StatusBar.setNetworkActivityIndicatorVisible(false);
            Request.LogError(e, apiUrl);
        });
    }
    static checkImageUrl(url) {
        if (typeof url === 'string') {
            if (Validator.validator(url, Validator.urlReg)) {
                return url;
            }
            else {
                return Request.getInstance().Api.HOST + url;
            }
        }
        if (Validator.validator(url.uri, Validator.urlReg)) {
            return url;
        }
        else {
            return Object.assign({}, url, { uri: Request.getInstance().Api.HOST + url.uri });
        }
    }
    static getErrorMessage(response) {
        let msg = '';
        if (Array.isArray(response.message)) {
        }
        else if (typeof response.message === 'string') {
            msg += response.message;
        }
        return msg;
    }
}
Request.makeQueryString = (params) => {
    if (!params) {
        return '';
    }
    let query = [];
    for (let key in params) {
        if (!params.hasOwnProperty(key)) {
            continue;
        }
        query.push(`${key}=${params[key]}`);
    }
    return '?' + query.join('&');
};
Request.makeFormData = (params) => {
    const formData = new FormData();
    for (let key in params) {
        if (!params.hasOwnProperty(key)) {
            continue;
        }
        formData.append(key, params[key]);
    }
    return formData;
};
Request.makeHeaders = (params, timestamp) => {
    return {
        'timestamp': timestamp,
    };
};
Request.LogSuccess = (response, frome) => {
    if (Request.getInstance().debug) {
        console.log('%c ', 'color"green', frome, response);
    }
};
Request.timeout = (ms, promise) => {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            reject(new Error("请求超时"));
        }, ms);
        promise.then(resolve, reject);
    });
};
export default Request;
